var app = getApp();
const qiniu = require("../../utils/qiniuUploader");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        addressData: [],     // 默认地址数据

        timeArray: ['1天', '3天', '7天', '30天'],   // 委托时间期限数据
        timeIndex:0,                // 当前选择时间

        title:'',           // 标题
        price:'',           // 预估价格
        phone:'',           // 联系方式
        ratio:'',           // 佣金比例
        times:'',           // 委托期限
        intro:'',           // 商品简介
        images:[],          // 图片详情
        files_num:0,        // 当前图片ID

        isSubmit:false,     // 是否提交

        qiniu_token:"",
        qiniu_link:"",
    },
    timesChange(e){
        this.setData({
			times: parseInt(this.data.timeArray[e.detail.value]),
            timeIndex: e.detail.value,
        })
    },
    blurCallBack(e){
        var val = e.detail.value;
        var name = e.target.dataset.name;
        if (name == 'title') { this.setData({ title: val }); return}
        if (name == 'price') { this.setData({ price: val }); return}
        if (name == 'phone') { this.setData({ phone: val }); return}
        if (name == 'ratio') { this.setData({ ratio: val }); return}
        if (name == 'intro') { this.setData({ intro: val }); return}
    },
    // 上传图片
    uploadImg(e) {
        var self = this;
        var images = this.data.images;

        var qiniu_link = this.data.qiniu_link;
        var qiniu_token = this.data.qiniu_token;
        var uploadURL = "https://upload.qiniup.com";

        wx.chooseImage({
            count: 9,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                const tempFilePaths = res.tempFilePaths;
                for (var i = 0; i < tempFilePaths.length; i++) {
                    var file = tempFilePaths[i];

                    var uploader = qiniu.upload(file, (res) => {
                        var url = res.imageURL;
                        var id = res.hash;

                        images.push({
                            id: id,
                            url: url
                        })
                        self.setData({
                            images: images,
                        })
                    }, (error) => {
                        console.log('error: ' + error);
                    }, {
                        uploadURL: uploadURL,
                        domain: qiniu_link,
                        uptoken: qiniu_token,
                    });
                }
            }
        })
    },
	deleteImg(e){
		var self = this;
		var id = e.target.dataset.id;
		var img = this.data.images;
		img.map((item,index) =>{
			if(item.id == id){
				img.splice(index,1)
			}
		})
		this.setData({
			images:img
		})
	},
    // 提交表单
    submit(){
        var data = {};
		var img = this.data.images || [];

        data.user_id = this.data.user_id;
        data.site_id = this.data.addressData.id;
        data.title = this.data.title;
        data.price = this.data.price;
        data.phone = this.data.phone;
        data.ratio = this.data.ratio;
        data.expire_date = parseInt(this.data.timeArray[this.data.timeIndex]);
        data.intro = this.data.intro;
        data.address_id = this.data.addressData.id;
        var imgs = [];

		img.map((item,index) => {
			imgs.push(item.url);
		});
        data.imgs = imgs.join(",")

        if (!data.address_id){
            wx.showToast({ image: '../../img/warning.png', title: '请选择地址' })
            return false;
        }
        if (!data.title){
            wx.showToast({ image: '../../img/warning.png', title: '请输入标题' })
            return false;
        }
        if (!data.price){
            wx.showToast({ image: '../../img/warning.png', title: '请输入预估价格' })
            return false;
        }
        if (!data.phone){
            wx.showToast({ image: '../../img/warning.png', title: '请输入联系方式' })
            return false;
        }
        if (!data.ratio){
            wx.showToast({ image: '../../img/warning.png', title: '请输入预估价格' })
            return false;
        }
        if (!data.expire_date){
            wx.showToast({ image: '../../img/warning.png', title: '请选择委托期限' })
            return false;
        }
        if (!data.intro){
            wx.showToast({ image: '../../img/warning.png', title: '请输入商品简介' })
            return false;
        }
        if (!data.imgs){
            wx.showToast({ image: '../../img/warning.png', title: '请上传商品图片' })
            return false;
        }
        this.submitEntrust(data);
    },
    // 表单填入完成且无错误
    submitEntrust(data){
        var self = this;
		var isSubmit = this.data.isSubmit;
		if (!isSubmit){
			this.setData({ isSubmit: true })
			wx.getStorage({
				key: 'user',
				success: function (res) {
					data.openid = res.data.openid;
					data.token = res.data.token;
					wx.request({
						url: app.url.requestUrl + '/entrust/addbuy',
						method: 'POST',
						data: data,
						success: function (res) {
							if (res.data.code == 1) {
								wx.showLoading({
									title: res.data.msg,
								})
								setTimeout(function () {
                                    wx.navigateBack({
                                        delta: 1
                                    })
									wx.hideLoading()
								}, 1000)
							} else {
                                self.setData({ isSubmit: false })
								wx.showToast({
									icon: 'none',
									title: res.data.msg,
								})
							}
						}
					})
				}
			})
		}
    },
    // 获取七牛所需数据
    getQiniuInfo() {
        var self = this;
        var url = "/upload/token";

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.setData({
                                qiniu_token: datas.data.token,
                                qiniu_link: datas.data.url
                            })
                        }
                    }
                })
            }
        })
    },
    // 生命周期函数--监听页面加载
    onLoad: function(options) {
		this.setData({
            user_id :options.id || ""
        })
        this.getQiniuInfo();
    }, 
    onShow(){
        var self = this;
        // /personal/default_address
        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + '/personal/default_address',
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                    },
                    header: {
                        'content-type': 'application/json'
                    },
                    success: function (res) {
                        if( res.data.code ==1 ){
                            self.setData({
                                addressData: res.data.data
                            })
                        }
                    }
                })
            }
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})